﻿using RabbitMQ.Client;
using System;

namespace Ec.NETCoreFramework.Common.MQ
{
    public class MsgPublish
    {
		private string _hostName = string.Empty;
		private string _userName = string.Empty;
		private string _pwd = string.Empty;
		private string _virtualHost = string.Empty;
		public MsgPublish(string hostName,string userName, string pwd,string virtualHost)
		{
			_hostName = hostName;
			_userName = userName;
			_pwd = pwd;
			_virtualHost = virtualHost;
		}
		public void Publish(string queuename, byte[] body)
		{
			var factory = new ConnectionFactory() { HostName = _hostName, Password = _pwd, UserName = _userName, 
				ClientProvidedName = queuename,VirtualHost=_virtualHost };
			using (var connection = factory.CreateConnection())
			using (var channel = connection.CreateModel())
			{
				channel.QueueDeclare(queue: queuename,
									 durable: true,
									 exclusive: false,
									 autoDelete: false,
									 arguments: null);

				var properties = channel.CreateBasicProperties();
				properties.Persistent = true;

				channel.BasicPublish(exchange: "",
									 routingKey: queuename,
									 basicProperties: properties,
									 body: body);
				Console.WriteLine(" [x] Sent {0}", body.Length);
			}
			Console.WriteLine(" Press [enter] to exit.");

		}
	}
}
